package com.zmm.myyimixian.ui.activity.login;

import android.content.Intent;
import android.support.design.widget.TextInputEditText;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zmm.myyimixian.MyApp;
import com.zmm.myyimixian.R;
import com.zmm.myyimixian.base.BaseActivity;
import com.zmm.myyimixian.db.MyUser;
import com.zmm.myyimixian.util.TextUtils;
import com.zmm.myyimixian.util.UIManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity {
    private Tencent mTencent;
    //回调接口
    private IUiListener loginListener;
    private IUiListener userInfoListener;
    private String SCOPE = "all";
    private String openID;//qq号唯一标识
    @BindView(R.id.login_toolbar)
    Toolbar loginToolbar;//toolbar
    @BindView(R.id.login_et_name)
    TextInputEditText loginEtName;//用户名
    @BindView(R.id.login_et_pass)
    TextInputEditText loginEtPass;//密码
    @BindView(R.id.login_btn_login)
    Button loginBtnLogin;//登陆按钮
    @BindView(R.id.login_tv_reg)
    TextView loginTvReg;//注册
    @BindView(R.id.login_tv_forget)
    TextView loginTvForget;//忘记密码
    @BindView(R.id.login_qq)
    ImageView loginQq;//qq登陆
    private String accessToken;
    private String expires;
    @Override
    protected void initView() {
        //初始化qq登陆
        initQqLogin();
        //处理返回按钮
        loginToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @OnClick({R.id.login_btn_login, R.id.login_tv_reg, R.id.login_qq})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_btn_login://登陆
                phoneLogin();
                break;
            case R.id.login_tv_reg://注册
                UIManager.startRegActivity(this);
                break;
            case R.id.login_qq: //qq登陆
                //第三方登录方法
                qqLogin();
                break;
        }
    }

    //qq登录功能
    public void qqLogin() {
        mTencent.login(this, SCOPE, loginListener);
    }

    //获取用户信息
    private void getUserInfo() {
        UserInfo info = new UserInfo(this, mTencent.getQQToken());
        info.getUserInfo(userInfoListener);
    }

    //初始化QQ登录分享的需要的资源
    private void initQqLogin() {
        mTencent = Tencent.createInstance("1105692097", getApplicationContext());
        //创建QQ登录回调接口
        loginListener = new IUiListener() {



            @Override
            public void onComplete(Object o) {
                //设置openid，如果不设置这一步的话无法获取用户信息
                JSONObject jo = (JSONObject) o;
                try {
                    openID = jo.getString("openid");
                    accessToken = jo.getString("access_token");
                    expires = jo.getString("expires_in");
                    queryUser();//查询Bmob是否由该qq用户

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(UiError uiError) {
                //登录失败后回调该方法
                Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                Log.e("LoginError:", uiError.toString());
            }

            @Override
            public void onCancel() {
                //取消登录后回调该方法
                Toast.makeText(LoginActivity.this, "取消登录", Toast.LENGTH_SHORT).show();
            }
        };
        //获取用户信息的回调接口
        userInfoListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                JSONObject jo = (JSONObject) o;
                Log.e("COMPLETE:", jo.toString());
                try {
                    JSONObject info = (JSONObject) o;
                    Log.e("TAG", jo.toString());
                    //获取QQ信息
                    String nickName = info.getString("nickname");
                    String gender = info.getString("gender");
                    String city = info.getString("city");
                    String figureurl = info.getString("figureurl_qq_2");
                    MyUser user = new MyUser();
                    user.setCity(city);
                    user.setFigureurl(figureurl);
                    user.setGender(gender);
                    user.setNick(nickName);
                    user.setOpenID(openID);
                    Toast.makeText(LoginActivity.this, "您还没有绑定手机号，请绑定！", Toast.LENGTH_SHORT).show();
                    //请绑定手机号
                    UIManager.startBoundActivity(LoginActivity.this,user);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(UiError uiError) {
            }

            @Override
            public void onCancel() {
            }
        };
    }
    //查询Bmob是否已经存在该qq用户
    private void queryUser() {
        BmobQuery<MyUser> query = new BmobQuery<MyUser>();
        query.addWhereEqualTo("openID", openID);//查询Bmob数据库是否已有该用户
        query.findObjects(LoginActivity.this, new FindListener<MyUser>() {
            @Override
            public void onSuccess(List<MyUser> object) {
                if (object.size() > 0 && object!=null) {
                    final MyUser user = object.get(0);
                    user.setPassword(user.getPass());
                    //存在的话直接登录
                    user.login(LoginActivity.this, new SaveListener() {
                        @Override
                        public void onSuccess() {
                            //qq已经绑定手机号 登陆成功
                            Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                            //保存用户信息
                            MyApp.setUserPhone(user.getUsername());
                            MyApp.setNickname(user.getNick());
                            MyApp.setGender(user.getGender());
                            MyApp.setFigureurl(user.getFigureurl());
                            MyApp.login();//登陆成功
                            UIManager.startMain(LoginActivity.this);
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            Toast.makeText(LoginActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                        }
                    });

                }else {
                    //qq号没有被绑定 获取qq信息
                    getUserInfo();
                    mTencent.setOpenId(openID);
                    mTencent.setAccessToken(accessToken, expires);
                }

            }

            @Override
            public void onError(int code, String msg) {
                //查询失败
                Log.e("SSS","*********************"+msg);
                Toast.makeText(LoginActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            if (resultCode == -1) {
                Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
                Tencent.handleResultData(data, loginListener);
            }
        }
    }

    private void phoneLogin() {
        //判断输入的数据是否有空字符
        if (TextUtils.isNull(loginEtName) || TextUtils.isNull(loginEtPass)) {
            loginEtName.setError("用户名或密码不能为空");
            return;
        }
        final String phone = loginEtName.getText().toString();
        String pass = loginEtPass.getText().toString();
        if (TextUtils.isMobileNO(phone)) {//验证输入的是否是手机号
            //将用户名和密码发给服务器进行校验
            // 使用BmobSDK提供的登录功能
            BmobUser.loginByAccount(this, phone, pass, new LogInListener<MyUser>() {

                @Override
                public void done(MyUser user, BmobException e) {
                    if (user != null) {
                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        //保存用户信息
                        MyApp.setUserPhone(user.getUsername());
                        MyApp.setNickname(user.getNick());
                        MyApp.setGender(user.getGender());
                        MyApp.setFigureurl(user.getFigureurl());
                        MyApp.login();//登陆成功
                        UIManager.startMain(LoginActivity.this);
                    } else {
                        Toast.makeText(LoginActivity.this, "用户名或密码错误！", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            loginEtName.setError("手机号格式错误,请重新输入");
        }
    }

}
